/*
 * @Author: your name
 * @Date: 2020-08-26 17:25:37
 * @LastEditTime: 2020-08-27 10:05:34
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /tools/statics/frac/frac.js
 */

var Fraction = {
    a: 0,
    b: 0,
    d: "",
    e: 0,
    fraction: function (num1, num2) {
        Fraction.a = num1;
        Fraction.b = num2;
        Fraction.appointment();
    },
    gcd: function (a, b) { //欧几里德算法
        a = Math.round(a), b = Math.round(b);
        return b == 0 ? a : Fraction.gcd(b, a % b); //消除浮点误差
    },
    appointment: function () { // 约分操作
        if (Fraction.a == 0 || Fraction.b == 1) return; // 如果分子是0或分母是1就不用约分了
        Fraction.e = Fraction.gcd(Fraction.a, Fraction.b);
        Fraction.a /= Fraction.e;
        Fraction.b /= Fraction.e;
    },
    toFraction: function () {
        Fraction.d = [Math.round(Fraction.a), Math.round(Fraction.b)];
    }
};

function decimalCheck(decimal) {
    //check dot
    let dot_count = 0;
    for (let i = 0; i < decimal.length; i++) {
        let c = decimal.substr(i, 1);
        if (c == '.')
            dot_count++;
        if (dot_count > 1) return false;
    }

    return true;
}

function decimal2Frac(decimal) {
    let decimal_len = function (decimal) {
        for (let i = 0; i < decimal.length; i++) {
            let c = decimal.substr(i, 1);
            if (c == '.')
                return (decimal.length - 1 - i);
        }
        return 0;
    }(decimal);
    let decimal_number = +decimal;
    let round = Math.floor(decimal_number);
    let denominator = 10 ** (decimal_len);
    let numerator = (decimal_number - round) * denominator;

    Fraction.fraction(numerator, denominator);
    Fraction.toFraction();

    return [round, Fraction.d]
}

function load(frac){
    let fraction = frac[1];
    let round_str = frac[0] != 0 ? ("<span class='round'>" + frac[0] + "</span><span class='sign'>&</span>") : "";
    let frac_str = "<span class='fraction'>" + fraction[0] + "/" + fraction[1] + "</span>";
    let commom_frac_str = "<div class='frac-line'><span class='fraction'>" + (fraction[0] + frac[0] * fraction[1]) + "/" + fraction[1] + "</span></div>"
    return ("<div class='frac-line'>" + round_str + frac_str + "</div>" + commom_frac_str);
}

$(document).ready(function () {
    $("button").on('click', function () {
        let decimal = $("#dot").val();
        let frac = decimal2Frac(decimal);
        let frac_str = load(frac);

        $("#frac-out").html(frac_str);
    });
});